using System.Collections.ObjectModel;
using System.Net.Http;
using System.Text;
using System.Text.Json;
using CommunityToolkit.Mvvm.ComponentModel;
using IMClient.Config;
using IMClient.Model.UI;
using System.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using IMClient.Model;
using IMClient.Model.Message;

namespace IMClient.ViewModels
{
    public partial class AddGroupWindowViewModel : ObservableObject
    {
        private readonly HttpClient _httpClient;

        [ObservableProperty] private string searchText = string.Empty;
        [ObservableProperty] private ObservableCollection<GroupViewModel> groupsList = new();
        [ObservableProperty] private string errorMessage = string.Empty;
        [ObservableProperty] private bool hasError;

        public AddGroupWindowViewModel()
        {
            _httpClient = new HttpClient
            {
                BaseAddress = new Uri(NetWorkConfig.BaseUrl)
            };
            PropertyChanged += AddGroupWindowViewModel_PropertyChanged;
        }

        private async void AddGroupWindowViewModel_PropertyChanged(object? sender, PropertyChangedEventArgs e)
        {
            if (e.PropertyName == nameof(SearchText) && SearchText.Length == 10)
            {
                await SearchGroup(SearchText);
            }
        }

        private async Task SearchGroup(string searchText)
        {
            try
            {
                HasError = false;
                ErrorMessage = string.Empty;
                GroupsList.Clear();

                var requestData = new { GroupId = searchText };
                var jsonContent = JsonSerializer.Serialize(requestData);
                var content = new StringContent(jsonContent, Encoding.UTF8, "application/json");

                var response = await _httpClient.PostAsync("/group/groupinfo", content);
                var jsonResponse = await response.Content.ReadAsStringAsync();

                using var document = JsonDocument.Parse(jsonResponse);
                var root = document.RootElement;
                
                var code = root.GetProperty("code").GetString();
                
                if (code == "0000")
                {
                    var groupData = root.GetProperty("data").GetProperty("group");
                    var members = root.GetProperty("data").GetProperty("members").EnumerateArray();

                    var group = new GroupViewModel
                    {
                        Id = groupData.GetProperty("groupId").GetString()!,
                        Name = groupData.GetProperty("groupName").GetString()!,
                        Avatar = groupData.GetProperty("avatar").GetString()!,
                        MemberCount = members.Count(),
                        ButtonText = "加入"
                    };
                    GroupsList.Add(group);
                }
                else
                {
                    HasError = true;
                    ErrorMessage = root.GetProperty("message").GetString() ?? "未知错误";
                }
            }
            catch (Exception ex)
            {
                HasError = true;
                ErrorMessage = $"搜索失败：{ex.Message}";
            }
        }

        [RelayCommand]
        private async Task JoinGroup(GroupViewModel group)
        {
            try
            {
                HasError = false;
                ErrorMessage = string.Empty;

                var requestData = new JoinGroupRequest
                {
                    GroupId = group.Id,
                    GroupName = group.Name,
                    GroupAvatar = group.Avatar,
                    GroupCreator = group.Creator!,
                    SenderId = User.UserId,
                    SenderName = User.UserName!,
                    SenderAvatar = User.UserAvatar,
                    Description = $"申请加入群组{group.Name}"  // 可以后续添加输入框让用户填写申请理由
                };

                var jsonContent = JsonSerializer.Serialize(requestData);
                var content = new StringContent(jsonContent, Encoding.UTF8, "application/json");

                var response = await _httpClient.PostAsync("/group/joinapply", content);
                var jsonResponse = await response.Content.ReadAsStringAsync();

                using var document = JsonDocument.Parse(jsonResponse);
                var root = document.RootElement;
                
                var code = root.GetProperty("code").GetString();
                var message = root.GetProperty("message").GetString();

                if (code == "0000")
                {
                    group.ButtonText = "已申请";
                    group.IsJoined = true;
                    
                    // 更新群组通知
                    // 创建群组通知
                    var notification = new GroupNotification
                    {
                        Name = group.Name,
                        Avatar = group.Avatar,
                        GroupId = group.Id,
                        GroupCreator = group.Creator!,
                        Action = "申请加入群组",
                        Time = DateTime.Now.ToString("yyyy-MM-dd"),
                        Message = "我：申请加入群组",
                        Status = "Pending"
                    };
                    
                    var contactsViewModel = ChatWindowViewModel.Instance.GetContactsViewModel();
                    var notificationViewModel = contactsViewModel?.GetGroupNotificationViewModel();
                    
                    notificationViewModel?.JoinGroupRequest(notification);
                    contactsViewModel?.CheckGroupNotification();
                }
                else
                {
                    HasError = true;
                    ErrorMessage = message ?? "未知错误";
                }
            }
            catch (Exception ex)
            {
                HasError = true;
                ErrorMessage = $"申请失败：{ex.Message}";
            }
        }
    }
}
